package com.fishv.fishvdianping.service.impl;

import java.util.Date;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fishv.fishvdianping.common.ErrorCode;
import com.fishv.fishvdianping.common.RedisConstant;
import com.fishv.fishvdianping.mapper.UserMapper;
import com.fishv.fishvdianping.model.domain.User;
import com.fishv.fishvdianping.model.entity.UserRequest;
import com.fishv.fishvdianping.model.vo.UserVO;
import com.fishv.fishvdianping.service.UserService;
import com.fishv.fishvdianping.utils.ThrowUtils;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author yuwei
 * @description 针对表【tb_user】的数据库操作Service实现
 * @createDate 2024-10-20 17:48:13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String getCode(String phone) {

        //避免重复发验证码
        String code = stringRedisTemplate.opsForValue().get(RedisConstant.CODE_PREFIX + phone);
        ThrowUtils.throwIf(StringUtil.isNotBlank(code), ErrorCode.TOO_MANY_REQUEST, "发送验证码过于频繁");
        //生成验证码
        code = RandomUtil.randomNumbers(6);
        //将验证码存入redis
        stringRedisTemplate.opsForValue().set(RedisConstant.CODE_PREFIX + phone, code, RedisConstant.CODE_TTL, TimeUnit.MINUTES);
        return code;
    }

    @Override
    public String login(UserRequest userRequest) {
        //获取验证码
        String code = stringRedisTemplate.opsForValue().get(RedisConstant.CODE_PREFIX + userRequest.getPhone());
        ThrowUtils.throwIf(StringUtil.isBlank(code), ErrorCode.NOT_FOUND_ERROR, "验证码不存在");
        //校验验证码
        ThrowUtils.throwIf(!code.equals(userRequest.getCode()), ErrorCode.PARAMS_ERROR, "验证码错误");
        //获取用户信息
        User user = query().eq("phone", userRequest.getPhone()).one();
        String token = RedisConstant.LOGIN_USER_KEY + UUID.randomUUID();

        if (user == null) {
            //保存到数据库中
            user = new User();
            user.setPhone(userRequest.getPhone());
            user.setPassword("");
            user.setNickName(token);
            user.setIcon("https://picsum.photos/200");
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            Boolean res = save(user);
            ThrowUtils.throwIf(!res, ErrorCode.OPERATION_ERROR, "保存用户失败");
        }

        //对象转Map
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        Map<String, Object> map = BeanUtil.beanToMap(userVO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

        //保存到 redis中
        stringRedisTemplate.opsForHash().putAll(token,map);
        stringRedisTemplate.expire(token, RedisConstant.LOGIN_USER_TTL, TimeUnit.MINUTES);

        return token;
    }
}




